dp geometry *2100

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

// Nome: Kalila and Dimna in the Logging Industry
// f(i) = f(j) + ai * bj
// b is decreasing
// a is increasing

typedef long long ll;

struct line{ll slope, y0;};

ll n, a[100010], b[100010];
deque <line> hull;

ll evaluate(line l, ll x){
    return l.slope * x + l.y0;
}

ll intersectionx(line a, line b){
    return (a.y0 - b.y0) / (b.slope - a.slope);
}

line query(ll x){
    while(hull.size() > 1){
        if(evaluate(hull[0], x) < evaluate(hull[1], x)) break;
        hull.pop_front();
    }
    return hull.front();
}

void update(line l){
    ll s = hull.size();
    while(s > 1){
        ll x1 = intersectionx(l, hull[s-1]);
        ll x2 = intersectionx(hull[s-2], hull[s-1]);
        if(x1 > x2) break;
        hull.pop_back();
        s--;
    }
    hull.push_back(l);
}

int main(){

    cin.tie(0)->sync_with_stdio(0);

    cin >> n;

    for(ll i=0;i<n;i++) cin >> a[i];
    for(ll i=0;i<n;i++) cin >> b[i];

    ll f[n];
    f[0] = 0;

    hull.push_back({b[0], f[0]});
    for(ll i=1;i<n;i++){
        f[i] = evaluate(query(a[i]), a[i]);
        update({b[i], f[i]});
    }

    cout << f[n-1] << '\n';

    return 0;
}
	  	  	  	 		     	 				 			 		


Comments

Submit
0 Comments
More Questions

1634B - Fortune Telling
1358A - Park Lighting
253C - Text Editor
365B - The Fibonacci Segment
75A - Life Without Zeros
1519A - Red and Blue Beans
466A - Cheap Travel
659E - New Reform
1385B - Restore the Permutation by Merger
706A - Beru-taxi
686A - Free Ice Cream
1358D - The Best Vacation
1620B - Triangles on a Rectangle
999C - Alphabetic Removals
1634C - OKEA
1368C - Even Picture
1505F - Math
1473A - Replacing Elements
959A - Mahmoud and Ehab and the even-odd game
78B - Easter Eggs
1455B - Jumps
1225C - p-binary
1525D - Armchairs
1257A - Two Rival Students
1415A - Prison Break
1271A - Suits
259B - Little Elephant and Magic Square
1389A - LCM Problem
778A - String Game
1382A - Common Subsequence